//
//  WDAnimateCellTableViewCell.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/13.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDAnimateCell.h"
#import "WDCircleView.h"
#import "WDProduct.h"
#import "WDMoneyTextField.h"
#import "WDCustomSheet.h"

typedef NS_ENUM(NSInteger, WDPickerType){
    WDPickerTypeTerm = 100,
    WDPickerTypeInterest
};

@interface WDAnimateCell () <UITextFieldDelegate, WDCustomSheetDelegate, WDTextFieldLimitDelegate>

@property (weak, nonatomic) IBOutlet WDMoneyTextField *moneyTextF;
/** 分期 */
@property (weak, nonatomic) IBOutlet UITextField *termTextF;
/** 金额范围 */
@property (weak, nonatomic) IBOutlet UILabel *moneyRangeLabel;
/** 年利率 */
@property (weak, nonatomic) IBOutlet UITextField *interestTextF;
/** 贷款 */
@property (weak, nonatomic) IBOutlet UILabel *loanMoneyLabel;
/** 利息 */
@property (weak, nonatomic) IBOutlet UILabel *interestLabel;
/** 月供 */
@property (weak, nonatomic) IBOutlet UILabel *monthlyLabel;
/** 动画父视图 */
@property (weak, nonatomic) IBOutlet UIView *AniamateView;
/** 圆环视图 */
@property (strong, nonatomic) WDCircleView *circleView;
/** 年利化率数组 */
@property (strong, nonatomic) NSArray *interests;
/** 数据缓存 */
@property (nonatomic, strong) NSMutableDictionary *textContents;
/** 分期数组 */
@property (nonatomic, strong) NSArray *terms;
@property (assign, nonatomic) BOOL isHaveDian;

@end

@implementation WDAnimateCell

- (NSMutableDictionary *)textContents
{
    if (_textContents == nil) {
        _textContents  = [NSMutableDictionary dictionary];
    }
    return _textContents;
}

+ (instancetype)animateCellWithTableView:(UITableView *)tableView
{
    static NSString *ID = @"animateCell";
    WDAnimateCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
    }
    return cell;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    //贷款金额TextF
    self.moneyTextF.limit.delegate = self;
    self.moneyTextF.limit.maxV = @"999999.99";
    self.moneyTextF.limit.digit = 2;
    
    //添加上圆环动画视图
    CGFloat lineW = 16;
    
    WDCircleView *circleView = [[WDCircleView alloc] initWithFrame:CGRectMake(self.AniamateView.bounds.origin.x + lineW / 2, self.AniamateView.bounds.origin.y + lineW / 2, self.AniamateView.bounds.size.width - lineW, self.AniamateView.bounds.size.height - lineW)];
    
    circleView.startValue = 0;
    circleView.lineWidth = lineW;
    
    [self.AniamateView addSubview:circleView];
    
    self.circleView = circleView;
    
    self.termTextF.tintColor = [UIColor clearColor];
    [self.termTextF addTarget:self action:@selector(termClick) forControlEvents:UIControlEventAllEvents];
    
    self.interestTextF.tintColor = [UIColor clearColor];
    [self.interestTextF addTarget:self action:@selector(interestClick) forControlEvents:UIControlEventAllEvents];
    
    //textFiled选择器
    UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, 1)];
    tempView.backgroundColor = [UIColor clearColor];
    self.termTextF.inputView = tempView;
    
    self.interestTextF.inputView = tempView;
    
}

- (void)termClick
{
    if ([self.termTextF isFirstResponder]) {
        
        WDCustomSheet *sheet = [[WDCustomSheet alloc] initWithButtons:self.terms isOriginal:YES];
        sheet.title = @"还款期数";
        sheet.tag = WDPickerTypeTerm;
        sheet.delegate = self;
        if ([_delegate isKindOfClass:[UIViewController class]]) {
            
            UIViewController *tempVC = (UIViewController *)_delegate;
            [tempVC.view addSubview:sheet];
        }
    }
}

- (void)interestClick
{
    if ([self.interestTextF isFirstResponder]) {
        
        WDCustomSheet *sheet = [[WDCustomSheet alloc] initWithButtons:self.interests isOriginal:YES];
        sheet.title = @"年利化率";
        sheet.tag = WDPickerTypeInterest;
        sheet.delegate = self;
        if ([_delegate isKindOfClass:[UIViewController class]]) {
            
            UIViewController *tempVC = (UIViewController *)_delegate;
            [tempVC.view addSubview:sheet];
        }
    }
}

- (void)cancel
{
    [self endEditing:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}

- (void)setProduct:(WDProduct *)product
{
    _product = product;
    
    if (self.textContents.count) {//缓存中有值，直接取
        self.moneyTextF.text = self.textContents[@"moneyText"];
        self.termTextF.text = self.textContents[@"termText"];
        self.interestTextF.text = self.textContents[@"interestText"];
        self.circleView.remark = YES;
    } else {//缓存中没有，从网络上获取
        
        self.moneyTextF.text = [NSString stringWithFormat:@"%.1f", [product.financeamount_end floatValue]];
        
        //按照逗号截取子串(分期)
        self.terms = [product.term componentsSeparatedByString:@","];
        
        self.termTextF.text = self.terms[0];
        
        //按照逗号截取子串(利息)
        self.interests = [product.interest_rate componentsSeparatedByString:@","];
        
        self.interestTextF.text = self.interests[0];
        
        //保存到缓存中
        [self.textContents setObject:self.moneyTextF.text forKey:@"moneyText"];
        [self.textContents setObject:self.termTextF.text forKey:@"termText"];
        [self.textContents setObject:self.interestTextF.text forKey:@"interestText"];
        self.circleView.remark = NO;
        
    }
    
    [_delegate chooseResult:self.moneyTextF.text term:self.termTextF.text interest:self.interestTextF.text];
    
    self.moneyRangeLabel.text = [NSString stringWithFormat:@"%.1f-%.1f", [product.financeamount_start floatValue], [product.financeamount_end floatValue]];
    
    [self drawCircle];
}

- (void)drawCircle
{
    self.loanMoneyLabel.text = self.moneyTextF.text;
    
    //计算利息和月供
    NSInteger money = [self.moneyTextF.text floatValue] *10000;
    
    NSInteger term = [self.termTextF.text integerValue];
    
    CGFloat interstRate = [self.interestTextF.text floatValue] / 100 / 12;
    
    //利息
    CGFloat interst = money * interstRate * term;
    
    //月供
    CGFloat monthly = (money + interst) / term;
    
    self.interestLabel.text = [NSString stringWithFormat:@"%.0f元", interst];
    
    self.monthlyLabel.text = [NSString stringWithFormat:@"%.0f", monthly];
    
    //画圆环
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.circleView.lineColr = WDNavSeleColor;
        
        self.circleView.anotherLineColor = ColorForRGB(0xf1a636);
        
            self.circleView.value = money * 1.0 / (money + interst);
        
    });
}

- (void)customSheet:(WDCustomSheet *)sheet clickButton:(NSUInteger)index
{
    if (sheet.tag == WDPickerTypeTerm) {
        
        self.termTextF.text = self.terms[index];
        
        [self.textContents setObject:self.termTextF.text forKey:@"termText"];
        
        [self.termTextF resignFirstResponder];
        
    } else if (sheet.tag == WDPickerTypeInterest) {
        
        self.interestTextF.text = self.interests[index];
        
        [self.textContents setObject:self.interestTextF.text forKey:@"interestText"];
        
        [self.interestTextF resignFirstResponder];
    }
    
    [_delegate chooseResult:self.moneyTextF.text term:self.termTextF.text interest:self.interestTextF.text];
    
    self.circleView.remark = YES;
    
    [self drawCircle];
}

#pragma mark - <WDTextFieldLimitDelegete>
- (void)valueChange:(id)sender
{
   
}

- (void)endEditing
{
    if ([self.moneyTextF.text floatValue] < [self.product.financeamount_start floatValue] || [self.moneyTextF.text floatValue] > [self.product.financeamount_end floatValue]) {
        self.moneyTextF.text = (NSString *)self.product.financeamount_end;
        [_delegate showErrorAlert:self.moneyTextF value:self.product.financeamount_end];
    } else {
        [self.textContents setObject:self.moneyTextF.text forKey:@"moneyText"];
    }
    
    self.circleView.remark = YES;
    
    [_delegate chooseResult:self.moneyTextF.text term:self.termTextF.text interest:self.interestTextF.text];
    
    [self drawCircle];
}

@end
